#include "Motor_Start.h"

void GPIO_4589_Init(void){
//    GPIO_InitTypeDef GPIO_InitStruct;
    
    
    RCC->APB1ENR |= (0x01<<1);
    RCC->AHB1ENR |= (0x01<<2);
    
    //GPIOB
    GPIOB->MODER |=(0x0A<<8);
    GPIOB->OSPEEDR |=(0x0F<<8);
    GPIOB->PUPDR |= (0x0A<<8);
    GPIOB->AFR[0] |= (0x22<<16);
    
    //GPIOC
    GPIOC->MODER |=(0x0A<<16);
    GPIOC->OSPEEDR |=(0x0F<<16);
    GPIOC->PUPDR |=(0x0A<<16);
    GPIOC->AFR[1] |=(0x22<<0);    
}

void TIM3_Init(void){
    GPIO_4589_Init();
    
    //
    TIM3->CR1 &= ~(0xFFFF);
    TIM3->CR1 |= (0x01<<2);//
    TIM3->CR1 |= (0x01<<7);//
    TIM3->DIER &= ~(0xFFFF) ;//
    TIM3->DIER |= (0x01);//
    TIM3->ARR =2000-1;//50Hz,一秒会产生500个计数溢出更新中断，但是PWM解析为20ms一次，一秒解析50次
    TIM3->PSC = 84-1;//100KHz    
    
    TIM3->CCER &= ~(0xFFFF);
    
    TIM3->CCMR1 |= (0x68<<0);
    TIM3->CCER |= 0x0001;//
    TIM3->CCR1 = 1000;
    
    //
    TIM3->CCMR1 |= (0x68<<8); //
    TIM3->CCER |= 0x0010;//
    TIM3->CCR2 = 1000;
    
    //
    TIM3->CCMR2 |= (0x68<<0);//
    TIM3->CCER |= 0x0100; //
    TIM3->CCR3 = 1000;
    

    TIM3->CCMR2 |= (0x68<<8);//
    TIM3->CCER |= 0x1000;//
    TIM3->CCR4 = 1000;
		
		HAL_NVIC_SetPriority(TIM3_IRQn, 14, 0);
    HAL_NVIC_EnableIRQ(TIM3_IRQn);
    
    TIM3->CR1 |= 0x01; //开启计数器
}

void PWM_SetRatio(uint16_t ch1,uint16_t ch2,uint16_t ch3,uint16_t ch4){
    TIM3->CCR1 = ch1;
    TIM3->CCR2 = ch2;
    TIM3->CCR3 = ch3;
    TIM3->CCR4 = ch4;
}


void TIM3_IRQHandler(void){
	if(TIM3->SR & (0x01<<0)) {
		TIM3->SR &= ~(0x01<<0);
	}
}
















